package com.bjpowernode.shop.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bjpowernode.shop.base.BaseManagerService;
import com.bjpowernode.shop.domain.SysMenu;
import com.bjpowernode.shop.domain.SysRoleMenu;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends BaseManagerService {


    @GetMapping("/nav")
    public ResponseEntity nav() {
        return ResponseEntity.ok(sysMenuService.getMenuAndAuth());
    }

    @GetMapping("/table")
    public ResponseEntity<List<SysMenu>> getAllMenuList() {
        return ResponseEntity.ok(sysMenuService.list());
    }

    @PostMapping
    @Transactional
    @CacheEvict(value = "sys:menu:list", key = "'SimpleKey []'")
    public ResponseEntity<Boolean> saveRole(@RequestBody SysMenu sysMenu) {
        boolean flag = sysMenuService.save(sysMenu);
        if (!flag) {
            throw new RuntimeException("新增菜单失败");
        }
        return ResponseEntity.ok(flag);
    }

    // 查询菜单信息
    @GetMapping("/info/{id}")
    @Transactional
    public ResponseEntity<SysMenu> menuInfo(@PathVariable Long id) {
        SysMenu sysMenu = sysMenuService.getById(id);
        return ResponseEntity.ok(sysMenu);
    }

    // 修改菜单信息
    @PutMapping
    @Transactional
    public ResponseEntity<Boolean> updateMenu(@RequestBody SysMenu sysMenu) {
        System.out.println("===sysMenu = " + sysMenu);

        boolean flag = sysMenuService.updateById(sysMenu);

        if (!flag)
            throw new RuntimeException("修改菜单失败");

        return ResponseEntity.ok(flag);
    }

    // 删除菜单信息
    @DeleteMapping("{id}")
    @Transactional
    public ResponseEntity<Boolean> delMenu(@PathVariable Long id) {
        System.out.println("===menuid = " + id);

        // 查询父菜单
        SysMenu sysMenu = sysMenuService.getOne(new LambdaQueryWrapper<SysMenu>().eq(
                        SysMenu::getMenuId, id
                )
        );

        // 非空则继续递归
        while (ObjectUtil.isNotNull(sysMenu)){
            // 删除子菜单，parentId=menuId
            sysMenuService.removeById(sysMenu);
            // 删除子菜单的role关联
            sysRoleMenuService.remove(new LambdaQueryWrapper<SysRoleMenu>().eq(
                    SysRoleMenu::getMenuId, sysMenu.getMenuId()
            ));
            // 查询子子菜单
            sysMenu = sysMenuService.getOne(new LambdaQueryWrapper<SysMenu>().eq(
                            SysMenu::getParentId, sysMenu.getMenuId()
                    )
            );
        }
        return ResponseEntity.ok(true);
    }
}
